#!/bin/sh

if [ $# -ne 1 ] && [ $# -ne 2 ]; then
	echo
	cat<<EOF
Usage: $0 FOLDERS...
       $0 -u

Mount encfs-encrypted FOLDERS.
With -u, unmount all encfs-mounted partitions.
EOF
	exit
fi

check() {
	for i ; do
		if ! command -v $i >/dev/null 2>&1; then
			echo "'$i' not found in PATH. Exiting." >&2
			exit 1
		fi
	done
}

mount() {
	check realpath encfs
	SOURCE="$(realpath "$1")"
	MOUNTPOINT="${SOURCE}_decrypted"
	mkdir -p "$MOUNTPOINT"
	if [ -z "$PASS" ]; then
		encfs "$SOURCE" "$MOUNTPOINT" || rmdir "$MOUNTPOINT"
	else
		echo "$PASS" | encfs --stdinpass "$SOURCE" "$MOUNTPOINT" || rmdir "$MOUNTPOINT"
	fi
}

unmount() {
	check findmnt fusermount dataindex

	while IFS= read -r i; do
		## Generate index on exit.
		folder=$(basename $(dirname "$i"))
		mkdir -p "$PERSONAL"/index/"$folder"
		dataindex "$i" | gpg --encrypt --recipient mail@ambrevar.xyz \
												 --output - > "$PERSONAL"/index/"$folder"/"$(basename "$i")".index.gpg
		unset folder
		fusermount -u "$i"
		rmdir "$i"
	done <<EOF
$(findmnt --noheadings --output=target encfs)
EOF
}

if [ "$1" = "-u" ]; then
	unmount
	exit 0
fi

if [ $# -gt 1 ]; then
	echo -n "EncFS Password: "
	read PASS
fi

for i; do
	mount "$i"
done
